<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Qbhy\HyperfAuth\AuthManager;

class ReSubmitMiddleware implements MiddlewareInterface
{
    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var \Hyperf\HttpServer\Contract\ResponseInterface
     */
    protected $response;

    /**
     * @Inject
     * @var AuthManager
     */
    protected $auth;

    /**
     * @Inject
     * @var Redis
     */
    protected $redis;

    /**
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($this->auth->check() && in_array($this->request->getMethod(), ['POST', 'PUT', 'DELETE'])) {
            $key =  env('APP_NAME') . ':admin:resubmit:' . md5($this->request->getPathInfo() . ':' . $this->auth->guard()->id() . ':' . $this->request->getAttribute('client-ip'));
            if (!$this->redis->set($key, 1, ['NX', 'EX' => 1])) {
                return $this->response->json([
                    'code' => 400,
                    'message' => 'request too fast',
                    'data' => [],
                ]);
            }
        }

        return $handler->handle($request);
    }
}
